package com.i2works.smartluolong.web.service.items.impl;

import com.google.common.collect.Lists;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.utils.basecommon.BaseCommonServiceImpl;
import com.i2works.smartluolong.utils.exception.DAOException;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.dal.items.dao.IItemsDAO;
import com.i2works.smartluolong.web.entity.items.ItemsDO;
import com.i2works.smartluolong.web.entity.items.ItemsQuery;
import com.i2works.smartluolong.web.entity.items.ItemsStepsDO;
import com.i2works.smartluolong.web.service.items.IItemsService;
import com.i2works.smartluolong.web.service.items.IItemsStepsService;
import com.xiaoleilu.hutool.collection.CollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Liu Yapeng
 * @date 2018-13-141 13:51:40
 */
@Service("itemsService")
public class ItemsServiceImpl extends BaseCommonServiceImpl<ItemsQuery, ItemsDO> implements IItemsService {


    @Autowired
    private IItemsDAO itemsDAO;

    @Autowired
    private IItemsStepsService itemsStepsService;

    @Override
    public void saveOrUpdate(ItemsDO itemsDO) throws ServiceException {
        try {
            if (itemsDO.getId() != null) {
                itemsDAO.update(itemsDO);
            } else {
                itemsDAO.save(itemsDO);
            }
            //删除部门分工
            itemsStepsService.deleteByItemId(itemsDO.getId());
            //添加部门分工
            if (CollUtil.isNotEmpty(itemsDO.getDepStepList()) && itemsDO.getId() != null) {
                List<ItemsStepsDO> stepList = emptyItemsStepsFilter(itemsDO.getDepStepList());
                for (ItemsStepsDO stepsDO : stepList) {
                    stepsDO.setItemsId(itemsDO.getId());
                    stepsDO.setStatus(GlobalConstant.status.TRUE);
                    stepsDO.setCreateName(itemsDO.getCreateName());
                    stepsDO.setUpdateName(itemsDO.getCreateName());
                    itemsStepsService.save(stepsDO);
                }
            }
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 过滤事项部门分工列表中的空对象
     */
    private List<ItemsStepsDO> emptyItemsStepsFilter(List<ItemsStepsDO> list) {
        List<ItemsStepsDO> result = Lists.newArrayList();
        if (CollUtil.isNotEmpty(list)) {
            for (ItemsStepsDO itemsStepsDO : list) {
                if (itemsStepsDO.getSteps() != null && itemsStepsDO.getItem() != null && itemsStepsDO.getOffice() != null) {
                    result.add(itemsStepsDO);
                }
            }
        }
        return result;
    }

}
